from pyglet import gl
import context
import world

import euclid
import math

class Camera: 
    def __init__(self):
        self._target_x_base = euclid.Vector3(1., 0., 0.)
        self._target_z_base = euclid.Vector3(0., 0., 1.)
        
        self._position = euclid.Vector3(*context._context.cam_settings.position)
        self._rot_x = 0.
        self._rot_y = context._context.cam_settings.direction
        
        self._up_axis = euclid.Vector3(*context._context.cam_settings.up_axis)

        self._speed = euclid.Vector3()
        self._mov = euclid.Vector3()
        self._target = euclid.Vector3()
        self._update_target()

    def lookAt(self):
        px, py, pz = self._position.xyz
        tx, ty, tz = (self._position + self._target).xyz
        ux, uy, uz = self._up_axis.xyz
    
        gl.gluLookAt(px, py, pz, tx, ty, tz, ux, uy, uz)
        
    def _update_target(self):        
        rot_y = euclid.Matrix4.new_rotatey(self._rot_y)
        vec_z = rot_y * self._target_x_base

        self._target = (rot_y * self._target_z_base).rotate_around(vec_z, self._rot_x)


    def rotate(self, dx, dy):
        #c'est pas des degres, mais on fait comme ca
        #c'est parceque c'est un programme tres particulier
        rot_x = math.radians(dy)
        rot_y = math.radians(dx)
        
        new_x = self._rot_x + -rot_x
        
        if new_x > math.pi / 3:
            new_x = math.pi / 3
        elif new_x < -math.pi / 3:
            new_x = -math.pi / 3
            
        self._rot_x = new_x
        self._rot_y += -rot_y
        
        self._update_target()
        self._update_mov()
        
    def _update_mov(self):
        #compute new pos

        rot_mat = euclid.Matrix4.new_rotatey(self._rot_y)
        self._mov = rot_mat * (self._speed)

    def accelerate(self, diff):
        self._speed += diff
        self._update_mov()

    def update(self, dt):
        self._position += self._mov * dt

